<?php
/**
 * TOP的数据请求模型
 * 
 * @version $Id: TopRequest.php 653 2013-01-23 08:04:34Z linsir123 $
 */
class TopRequest
{
	/**
	 * @var 阿里妈妈PID
	 */
	public $pId;
	
	/**
	 * @var 渠道号
	 * // 格式:英文和数字组成;长度不能大于12个字符
	 */
	public $outerCode;
	
	/**
	 * @var 是否开启缓存
	 */
	public $caching = true;
	
	/**
	 * @var 缓存的过期时间(3天)
	 */
	public $cacheLifeTime = 259200;
	
	/**
	 * @var 数据统计
	 */
	public $statistics;
	
	/**
	 * 构造函数
	 */
	public function __construct()
	{
		$this->outerCode = 'e35go';
		$this->pId = App::O('taobaoke.pId');
		///
		App::V('taobao');
	}
	
	/**
	 * 析构函数
	 */
	public function __destruct()
	{
		// App::log($this->statistics, "TopRequest");
	}
	
	/**
	 * 取得分类信息[商品]
	 */
	public function itemcatsGet($cIds = "", $parentCid = 0)
	{
		$this->_statistics("itemcatsGet");
		
		///
		$api = 'itemcatsGet';
		
		///
		$key = $this->_getCacheKey(array($cIds, $parentCid));
		$data = $this->_getCache($api, $key);
		if ( ! $data) {
			$req = new ItemcatsGetRequest();
			$req->setFields("cid,parent_cid,name,is_parent");
			if ($cIds) 
				$req->setCids($cIds);
			else 
				$req->setParentCid($parentCid);
				
			///
			$data = array();
			$tmp = $this->_callTopApi($req);
			if (isset($tmp['item_cats'])) {
				App::V('pinyin');
				///
				foreach ($tmp['item_cats']['item_cat'] as $v) 
					$data[] = array(
						'id' => $v['cid'],
						'pid' => $v['parent_cid'],
						'title' => $v['name'],
						'pinyin' => string2pinyin($v['name']),
					);
					
				$this->_saveCache($api, $key, $data);
			}
		}
		
		return $data;
	}
	
	/**
	 * 取得分类信息[店铺]
	 */
	public function shopcatsListGet()
	{
		$this->_statistics("shopcatsListGet");
		
		///
		$api = 'shopcatsListGet';
		
		///
		$key = $api;
		$data = $this->_getCache($api, $key);
		if ( ! $data) {
			$req = new ShopcatsListGetRequest();
			$req->setFields("cid,parent_cid,name,is_parent");
			
			///
			$data = array();
			$tmp = $this->_callTopApi($req);
			if (isset($tmp['shop_cats'])) {
				App::V('pinyin');
				///
				foreach ($tmp['shop_cats']['shop_cat'] as $v) 
					$data[] = array(
						'id' => $v['cid'],
						'title' => $v['name'],
						'pinyin' => string2pinyin($v['name']),
					);
					
				$this->_saveCache($api, $key, $data);
			}
		}
		
		return $data;
	}
	
	/**
	 * 获取商品信息
	 */
	public function itemGet($iId)
	{
		$this->_statistics("itemGet");
		
		/* 验证必填数据 */
		if (empty($iId)) 
			return array();
			
		///
		$req = new ItemGetRequest();
		$req->setFields("detail_url,num_iid,props_name,title,nick,type,cid,seller_cids,props,input_pids,input_str,desc,pic_url,num,valid_thru,list_time,delist_time,stuff_status,location,price,post_fee,express_fee,ems_fee,has_discount,freight_payer,has_invoice,has_warranty,has_showcase,modified,increment,approve_status,postage_id,product_id,auction_point,property_alias,item_img,prop_img,sku,video,outer_id,is_virtual");
		$req->setNumIid($iId);
		
		///
		$tmp = $this->_callTopApi($req, 'xml');
		if (isset($tmp['item'])) 
			$data = $tmp['item'];
		else 
			$data = array();
			
		return $data;
	}
	
	/**
	 * 获取店铺信息
	 */
	public function shopGet($nick)
	{
		$this->_statistics("shopGet");
		
		/* 验证必填数据 */
		if (empty($nick)) 
			return array();
			
		///
		$req = new ShopGetRequest();
		$req->setFields('sid,cid,nick,title,desc,pic_path,created,shop_score');
		$req->setNick($nick);
		
		///
		$tmp = $this->_callTopApi($req, 'xml');
		if (isset($tmp['shop'])) 
			$data = $tmp['shop'];
		else 
			$data = array();
			
		return $data;
	}
	
	/**
	 * 取得商品
	 */
	public function taobaokeItemsDetailGet($iId)
	{
		$this->_statistics("taobaokeItemsDetailGet");
		
		/* 验证必填数据 */
		if (empty($iId)) 
			return array();
			
		///
		$req = new TaobaokeItemsDetailGetRequest();
		$req->setFields("click_url,shop_click_url,seller_credit_score");
		$req->setNumIids($iId);
		$req->setPid($this->pId);
		$req->setOuterCode($this->outerCode);
		
		///
		$tmp = $this->_callTopApi($req);
		if ($tmp['total_results'] >= 1) 
			$data = $tmp['taobaoke_item_details']['taobaoke_item_detail'][0];
		else 
			$data = array();
			
		///
		return $data;
	}
	
	/**
	 * 推管商品
	 */
	public function taobaokeItemsGet($params = array())
	{
		$this->_statistics("taobaokeItemsGet");
		
		/* 验证必填数据 */
		if (empty($params['keyword']) && empty($params['cid'])) 
			return array();
			
		///
		$params = array_merge(array(
			'fields'	=> "num_iid,seller_credit_score,title,nick,pic_url,price,click_url,commission,commission_rate,commission_num,commission_volume,shop_click_url,seller_credit_score,item_location,volume",
			'show'		=> 20,
		), $params);
		$methods = array(
			'fields' 		=> 'setFields', 
			'p'				=> 'setPageNo', 
			'cid' 			=> 'setCid', 
			'sort' 			=> 'setSort', 
			'show' 			=> 'setPageSize', 
			'keyword' 		=> 'setKeyword', 
			'start_price' 	=> 'setStartPrice', 
			'end_price'		=> 'setEndPrice', 
		);
		
		///
		$req = new TaobaokeItemsGetRequest();
		$tmp = $this->_doRequest($req, $methods, $params, true);
		if (isset($tmp['taobaoke_items'])) {
			$total = $tmp['total_results'];
			$data = array(
				$tmp['taobaoke_items']['taobaoke_item'], 
				ceil($total/$params['show']),
				$total
			);
		} else 
			$data = array();
			
		///
		return $data;
	}
	
	/**
	 * 推管商品
	 */
	public function taobaokeItemsCouponGet($params = array())
	{
		$this->_statistics("taobaokeItemsCouponGet");
		
		///
		$params = array_merge(array(
			'show'		=> 20,
			'fields'	=> "num_iid,title,nick,pic_url,price,click_url,commission,commission_rate,commission_num,commission_volume,shop_click_url,seller_credit_score,item_location,volume,coupon_price,coupon_rate,coupon_start_time,coupon_end_time,shop_type",
		), $params);
		$methods = array(
			'fields' 	=> 'setFields', 
			'cid' 		=> 'setCid', 
			'keyword' 	=> 'setKeyword', 
			'sort' 		=> 'setSort', 
			'show'		=> 'setPageSize', 
			'p'			=> 'setPageNo', 
		);
		
		///
		$req = new TaobaokeItemsCouponGetRequest();
		$tmp = $this->_doRequest($req, $methods, $params, true);
		if (isset($tmp['taobaoke_items'])) {
			$total = $tmp['total_results'];
			$data = array(
				$tmp['taobaoke_items']['taobaoke_item'], 
				ceil($total/$params['show']),
				$total
			);
		} else 
			$data = array();
			
		///
		return $data;
	}
	
	/**
	 * 取得商品相关
	 */
	public function taobaokeItemsRelateGet($params = array())
	{
		$this->_statistics("taobaokeItemsRelateGet");
		
		///
		$params = array_merge(array(
			'maxCount'	=> 20,
			'sort'		=> 'commissionRate_desc',
			'fields'	=> "num_iid,title,nick,pic_url,price,click_url,commission,commission_rate,commission_num,commission_volume,shop_click_url,seller_credit_score,item_location,volume",
		), $params);
		$methods = array(
			'fields'		=> 'setFields', 
			'cid'			=> 'setCid', 
			'sort'			=> 'setSort', 
			'sellerId'		=> 'setSellerId', 
			'relateType'	=> 'setRelateType', 
			'maxCount'		=> 'setMaxCount', 
		);
		
		///
		$req = new TaobaokeItemsRelateGetRequest();
		$tmp = $this->_doRequest($req, $methods, $params, true);
		if (isset($tmp['taobaoke_items'])) 
			$data = $tmp['taobaoke_items']['taobaoke_item'];
		else 
			$data = array();
			
		///
		return $data;
	}
	
	/**
	 * 推管店铺
	 */
	function taobaokeShopsGet($params = array())
	{
		$this->_statistics("taobaokeShopsGet");
		
		/* 验证必填数据 */
		if (empty($params['keyword']) && empty($params['cid'])) 
			return array();
			
		///
		$params = array_merge(array(
			'show'			=> 20,
			'startCredit'	=> "1diamond",
			'endCredit'		=> "5goldencrown",
			'fields'		=> "seller_nick,user_id,shop_title,click_url,seller_credit,shop_type",
		), $params);
		$methods = array(
			'fields'		=> 'setFields', 
			'cid'			=> 'setCid', 
			'keyword'		=> 'setKeyword', 
			'sortField'		=> 'setSortField', 
			'sortType'		=> 'setSortType', 
			'show'			=> 'setPageSize', 
			'p'				=> 'setPageNo', 
			//'startCredit'	=> 'setStartCredit', 
			//'endCredit'		=> 'setEndCredit', 
		);
		
		///
		$req = new TaobaokeShopsGetRequest();
		$tmp = $this->_doRequest($req, $methods, $params, true);
		if (isset($tmp['taobaoke_shops'])) {
			$total = $tmp['total_results'];
			$totalPage = ceil($total/$params['show']);
			$data = array(
				$tmp['taobaoke_shops']['taobaoke_shop'], 
				$totalPage,
				$total
			);
		} else 
			$data = array();
			
		///
		return $data;
	}
	
	/**
	 * 取得店铺相关
	 */
	public function taobaokeShopsRelateGet($params = array())
	{
		$this->_statistics("taobaokeShopsRelateGet");
		
		///
		$params = array_merge(array(
			'maxCount'	=> 18,
			'sort'		=> 'commissionRate_desc',
			'fields'	=> "seller_nick,user_id,shop_title,click_url,seller_credit,shop_type",
		), $params);
		$methods = array(
			'fields' 		=> 'setFields', 
			'sort' 			=> 'setSort', 
			'sellerNick' 	=> 'setSellerNick', 
			'maxCount' 		=> 'setMaxCount', 
		);
		
		///
		$req = new TaobaokeShopsRelateGetRequest();
		$tmp = $this->_doRequest($req, $methods, $params, true);
		if (isset($tmp['taobaoke_shops'])) 
			$data = $tmp['taobaoke_shops']['taobaoke_shop'];
		else 
			$data = array();
			
		///
		return $data;
	}
	
	/**
	 * 获取交易报告
	 */
	public function taobaokeReportGet($params = array())
	{
		$this->_statistics("taobaokeReportGet");
		
		///
		$params = array_merge(array(
			'fields'	=> "app_key,outer_code,trade_id,pay_time,pay_price,num_iid,item_title,item_num,category_id,category_name,shop_title,commission_rate,commission,iid,seller_nick",
		), $params);
		$methods = array(
			'fields'	=> 'setFields', 
			'date' 		=> 'setDate', 
			'p' 		=> 'setPageNo', 
			'show' 		=> 'setPageSize', 
		);
		
		///
		$req = new TaobaokeReportGetRequest();
		$data = $this->_doRequest($req, $methods, $params);
		
		///
		return $data;
	}
	
	
	/// 以下为私有方法 /// 
	
	
	/**
	 * 设置查询对象属性
	 */
	private function _doRequest($req, $methods, $params, $taobaoke = false, $format = 'json')
	{
		if ($taobaoke) {
			$params['pid'] = $this->pId;
			$params['outerCode'] = $this->outerCode;
			///
			$methods['pid'] = 'setPid';
			$methods['outerCode'] = 'setOuterCode';
		}
		
		///
		foreach ($methods as $f => $v) {
			if (isset($params[$f])) 
				call_user_func_array(array($req, $v), array($params[$f]));
		}
		
		///
		return $this->_callTopApi($req, $format);
	}
	
	/**
	 * 调用API
	 */
	private function _callTopApi($req, $format = 'json')
	{
		$sender = M::topSender();
		///
		return $sender->execute($req, $format);
	}
	
	/**
	 * 根据查询条件构造唯一的key
	 */
	private function _getCacheKey($params)
	{
		$key = serialize($params);
		return md5($key);
	}
	
	/**
	 * 缓存目录
	 */
	private function _getCacheFile($api, $key)
	{
		$dir = CACHE_DIR.'taobao/'. $api .'/'. $key[0] .'/'. $key[1] .'/';
		lpDir::make($dir);
		
		///
		return $dir . $key .'.php';
	}
	
	/**
	 * 将查询结果进行缓存
	 */
	private function _saveCache($api, $key, $data)
	{
		if ($this->caching) {
			$file = $this->_getCacheFile($api, $key);
			$content = "<?php \r\n return ".var_export($data, true).';';
			file_put_contents($file, $content);
		}
	}
	
	/**
	 * 取得查询缓存
	 */
	private function _getCache($api, $key)
	{
		if ($this->caching) {
			$file = $this->_getCacheFile($api, $key);
			if (file_exists($file)) {
				$time = filemtime($file);
				if (time() - intval($time) < $this->cacheLifeTime) 
					return require($file);
			}
		}
		
		return false;
	}
	
	/**
	 * API调用统计
	 */
	private function _statistics($api)
	{
		if (isset($this->statistics[$api])) 
			$this->statistics[$api]++;
		else 
			$this->statistics[$api] = 1; 
	}
}
